<template>
  <div>
    <el-form labelWidth="40px">
      <el-form-item label="输入">
        <el-input-number v-model="inputValue"></el-input-number>
      </el-form-item>
      <el-form-item label="结果">
        <el-text>{{ result }}</el-text>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="loading" @click="handleCalc">
          计算斐波那契
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { AppWorker } from '@lib/worker'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'

import type IDepts from './workers/depts'
import runWithDepts from './workers/runWithDepts?worker&url'

const appWorker = new AppWorker({
  workerName: 'runWithDepts',
  workerPath: runWithDepts
})

const loading = ref(false)
const inputValue = ref(50)
const result = ref('')

async function handleCalc() {
  try {
    loading.value = true
    const res = await appWorker.run((depts: typeof IDepts, n) => {
      const { memoize } = depts

      // @see https://www.cnblogs.com/qiqi715/p/10026355.html
      const fibonacci = memoize((n: number): number => {
        if (n < 0) throw new Error('输入的数字不能小于0')
        if (n == 1 || n == 2) {
          return 1
        } else {
          return fibonacci(n - 1) + fibonacci(n - 2)
        }
      })

      return fibonacci(n)
    }, inputValue.value)
    result.value = res
  } catch (error: any) {
    console.error(error)
    ElMessage.error({ message: error.message })
  } finally {
    loading.value = false
  }
}
</script>
